package com.shawn.springboot.integeration.common.config.shiro.realm;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.shawn.springboot.integeration.common.config.shiro.token.JWTToken;
import com.shawn.springboot.integeration.common.config.shiro.token.JWTUtil;
import com.shawn.springboot.integeration.system.model.pojo.SysUser;
import com.shawn.springboot.integeration.system.service.ISysMenuService;
import com.shawn.springboot.integeration.system.service.ISysRoleService;
import com.shawn.springboot.integeration.system.service.ISysUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

/**
 * @author shawn
 * @description: 自定义 Realm,主要实现认证和授权
 * @date 2023/12/17
 */
@Component
public class CustomRealm extends AuthorizingRealm{
    private Logger log = LoggerFactory.getLogger(CustomRealm.class);
    @Resource
    private ISysUserService sysUserService;
    @Resource
    private ISysRoleService roleService;
    @Resource
    private ISysMenuService menuService;
    // 验证令牌对象是否为自己定义的令牌封装类型。
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authToken)
            throws AuthenticationException {
        log.info("token 认证开始...");
        // 校验中 token 中是否存在用户名
        String token = (String) authToken.getCredentials();
        String username = JWTUtil.getUsername(token);
        if (StrUtil.isBlank(username)) {
            throw new IncorrectCredentialsException();
        }
        // 校验数据库中用户是否存在
        SysUser user = sysUserService.selectUserByLoginName(username);
        if (ObjectUtil.isNull(user)) {
            throw new IncorrectCredentialsException();
        }
        // 校验 token 是否有效
        if(!JWTUtil.verify(token, username,user.getPassword())) {
            throw new IncorrectCredentialsException();
        }
        log.info("token 认证结束...");
        // 返回授权信息
        return new SimpleAuthenticationInfo(token, token, getName());
    }
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 从 token 中获取用户名
        String username = JWTUtil.getUsername(principals.toString());
        // 从数据库中查询用户对应的角色和权限
        Set<String> roleSet = new HashSet<>();
        Set<String> permissionSet = new HashSet<>();
        SysUser user = sysUserService.selectUserByLoginName(username);
        if (user.isAdmin()) {
            roleSet.add("admin");
            permissionSet.add("*:*:*");
        } else {
            roleSet = roleService.selectRoleKeys(user.getUserId());
            permissionSet = menuService.selectPermsByUserId(user.getUserId());
        }
        // 设置授权信息(角色和权限)
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addRoles(roleSet);
        authorizationInfo.addStringPermissions(permissionSet);
        return authorizationInfo;
    }
}
